package com.clusterswisdom.horn.api.tmall;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.event.EventPool;
import com.clusterswisdom.horn.api.ioc.event.HornEvent;
import com.clusterswisdom.horn.api.tmall.config.TmallApplication;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;

public class HornTmcClient extends TmcClient implements MessageHandler {
	
	private Logger log = LoggerFactory.getLogger(HornTmcClient.class);
	
	public HornTmcClient(TmallApplication applicaiton) {
		super(applicaiton.getWsUrl(), applicaiton.getAppKey(), applicaiton.getAppSecret(), "default");
		super.setMessageHandler(this);
	}

	@Override
	public void onMessage(Message message, MessageStatus status) throws Exception {
		try {
			Thread.sleep(1000);
			log.debug("get a message " + message.getTopic() + " : " + message.getContent());
			String[] topics = message.getTopic().split("[_]");
			String channel = TmallInstance.getInstance().getConfig().getChannel();
			JSONObject param = JSON.parseObject(message.getContent());
			param.put("userNick", message.getUserNick());
			param.put("id", message.getId());
			param.put("userNick", message.getOutgoingTime());
			
			HornEvent event = new HornEvent(saveMessageToDb(message), channel, topics[1], topics[2], param);
			EventPool.getPool().executeEvent(event);
			
		} catch (Exception e) {
			e.printStackTrace();
			status.fail();
			
		}
	}
	
	private Long saveMessageToDb(Message message) {
		return null;
	}
}